package edu.java.lectures.lec12.threads.synchronization.dynamic.msgbox;

import java.util.ArrayList;
import java.util.List;

public class MsgBox {

    private static final int CAPACITY = 4;

    private List<String> msgQueue;

    public MsgBox() {
	msgQueue = new ArrayList<String>();
    }

    // public synchronized String getMessage() throws InterruptedException {
    public String getMessage() throws InterruptedException {
	synchronized (this) { // MUST LOCK AS LESS AS POSSIBLE PART OF THE
	    // CODE
	    // if (msgQueue.isEmpty()) { // WORKS BUT ONLY ONCE
	    while (msgQueue.isEmpty()) {
		System.out.println(Thread.currentThread().getName()
			+ " go to wait, because the msgBox is empty.");
		wait();
	    }
	    String message = msgQueue.remove(0);
	    if (msgQueue.size() < CAPACITY) {
		notifyAll();
	    }
	    return message;
	}
    }

    public synchronized void putMessage(String msg) throws InterruptedException {
	// if (msgQueue.size() >= CAPACITY) {
	while (msgQueue.size() >= CAPACITY) {
	    System.out.println(Thread.currentThread().getName()
		    + " go to wait, because the msgBox is full ("
		    + msgQueue.size() + " msgs)");
	    wait();
	}
	msgQueue.add(msg);
	notifyAll();
    }
}
